package br.uniceub.fsw.agenda.controller;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Servlet base do qual todos os outros servlets serão "extendidos"
 * 
 * O método processRequest será implementado de maneira a receber todas as
 * requisicoes e, usando reflection, passar a requisicao para o metodo
 * especificado pelo parametro 'method'. (comportamento semelhante ao 
 * ActionDispatcher do struts).
 * 
 * 05/04/2008
 * @author Rodrigo Uchôa - rodrigo.uchoa@yahoo.com
 */
public class GenericServlet extends HttpServlet {
   
    /** 
    * Processa requisicoes GET e POST e a envia para o metodo indicado pelo
    * parametro 'method'. 
    * 
    *
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       //usando reflection pra chamar o metodo correspondente.
        try {
            String methodName = request.getParameter("method");
            
            Class requestClazz = Class.forName("javax.servlet.http.HttpServletRequest");
            Class responseClazz = Class.forName("javax.servlet.http.HttpServletResponse");            
            Class clazz = this.getClass();                       
            
            Method methodToCall = clazz.getDeclaredMethod(methodName, requestClazz, responseClazz);            
            methodToCall.invoke(this, request, response);
            
        } catch (NoSuchMethodException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
